<template>
	<div>
		<!-- 课程列表 -->
		<div v-if="!isEditor">
			<div class="topButton">
				<el-button type="primary" plain size="mini" @click="isEditor = true">新增课程</el-button>
			</div>
			<el-table :data="pageData.items" :header-cell-style="headerFirst" :span-method="objectSpanMethod" border style="width: 100%">
				<el-table-column prop="date" label="日期">
					<el-table-column prop="courseDate" label="" width="100"></el-table-column>
					<el-table-column prop="timeSlot" label="" width="60"></el-table-column>
				</el-table-column>
				<el-table-column prop="name" label="时间">
					<template slot-scope="scope">
						{{ scope.row.startTime }}-{{ scope.row.endTime }}
					</template>
				</el-table-column>
				<el-table-column prop="topic" label="课题"></el-table-column>
				<el-table-column prop="keyWord" label="关键字"></el-table-column>
				<el-table-column prop="expertName" label="授课专家"></el-table-column>
				<el-table-column label="操作">
					<template slot-scope="scope">
						<el-button type="text" size="mini" @click="lookcourse(scope.row)">查看</el-button>
						<el-button type="text" size="mini" @click="deletecourse(scope.row)">删除</el-button>
					</template>
				</el-table-column>
			</el-table>
			<!-- <pagina-tion :totalNum="pageData.totalNum" @paginaClick="paginaClick"></pagina-tion> -->
		</div>
		<!-- 新增、编辑课程 -->
		<div v-else class="EditorForm">
			<el-form label-width="100px" :model="formLabelAlign">
				<el-form-item label="课题：">
					<el-input v-model="formLabelAlign.topic" placeholder="请输入课题" class="formInput"></el-input>
				</el-form-item>
				<el-form-item label="关键词：">
					<el-input v-model="formLabelAlign.keyWord" placeholder="请输入关键词" class="formInput"></el-input>
				</el-form-item>
				<el-form-item label="日期：">
					<el-date-picker v-model="formLabelAlign.courseDate" type="date" class="formInput" placeholder="选择日期" format="yyyy-MM-dd"
					 value-format="yyyy-MM-dd">
					</el-date-picker>
				</el-form-item>
				<el-form-item label="时间：">
					<el-time-select v-model="formLabelAlign.startTime" :picker-options="{
					    start: '00:00',
					    step: '00:15',
					    end: '23:59'
					  }"
					 @change="selectStratTime" placeholder="选择时间">
					</el-time-select>
					<span style="margin: 0 27px;">-</span>
					<el-time-select v-model="formLabelAlign.endTime" :picker-options="{
					    start: formLabelAlign.startTime,
					    step: '00:15',
					    end: '23:59',
						minTime: formLabelAlign.startTime
					  }"
					 placeholder="选择时间">
					</el-time-select>
				</el-form-item>
				<el-form-item label="时间段：">
					<el-select v-model="formLabelAlign.timeSlot" disabled placeholder="请选择授课时间段" class="formInput">
						<el-option label="上午" value="上午"></el-option>
						<el-option label="下午" value="下午"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="专家：">
					<el-select v-if="menbersList" v-model="formLabelAlign.experId" placeholder="请选择专家" class="formInput">
						<el-option v-for="item in menbersList.items" :label="item.expertName" :value="item.expertId"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="课件：">
					<div class="">
						<div class="fileListName" v-if="fileListName && fileListName.length > 0" v-for="(item, index) in fileListName"
						 :key="index">
							{{ item }}
							<i class="el-icon-close fileListNameIcon" @click="deleteFiles(index)"></i>
						</div>
						<el-upload class="upload-demo" action="" :http-request="uploadFiles" :show-file-list="false">
							<el-button type="primary" :loading="uploadLoading" plain>上传附件</el-button>
						</el-upload>
					</div>
				</el-form-item>
				<el-form-item label="文章：">
					<vue-ueditor-wrap v-model="formLabelAlign.articleAttachment" class="VueUeditorWrap" :config="myConfig"></vue-ueditor-wrap>
				</el-form-item>
			</el-form>

			<div class="btnBox">
				<el-button type="primary" round @click="goBack">返回</el-button>
				<el-button type="primary" round @click="submit">保存/修改</el-button>
			</div>
		</div>
	</div>
</template>

<script>
	import VueUeditorWrap from 'vue-ueditor-wrap'
	export default {
		components: {
			VueUeditorWrap
		},
		data() {
			return {
				companyId: '',
				pageData: '',
				uploadLoading: false,
				myConfig: {
					//禁用编辑器
					readonly: false,
					// 编辑器不自动被内容撑高
					autoHeightEnabled: false,
					// 初始容器高度
					initialFrameHeight: 420,
					// 初始容器宽度
					initialFrameWidth: '100%',
					// 上传文件接口（这个地址是我为了方便各位体验文件上传功能搭建的临时接口，请勿在生产环境使用！！！）
					// serverUrl: 'https://chenzhouhuang.utools.club/ueditorConfig',
					// serverUrl: 'https://kwkxcx.com/ueditorConfig',
					serverUrl: 'http://192.168.0.115:8080/ueditor1_4_3-utf8-jsp/jsp/controller.jsp?action=config',
					// UEditor 资源文件的存放路径，如果你使用的是 vue-cli 生成的项目，通常不需要设置该选项，vue-ueditor-wrap 会自动处理常见的情况，如果需要特殊配置，参考下方的常见问题2
					UEDITOR_HOME_URL: '/UEditor/'
				},
				isEditor: false,
				isLookList: false, // 是否查看
				formLabelAlign: {
					topic: '', // 主题
					keyWord: '', // 关键词
					courseDate: '', // 课程日期
					startTime: '', // 开始时间
					endTime: '', // 结束时间
					timeSlot: '', // 授课时间段
					experId: '', // 专家ID
					courseId: '', // 培训班ID
					articleAttachment: '', // 富文本
					files: [], // 课件HTTP集合
					// dates: [] // 页面绑定的时间
				},
				menbersList: '', // 专家列表
				fileListName: [], // 上传的文件名
				// 修改时用到的课程id
				updateCourseId: '',
				// 处理表格合并
				newArry: [],
				dataDate: new Map() // 得到所有数据的时间

			};
		},
		mounted() {
			this.companyId = this.$store.state.company.selectCompanyId ?
				this.$store.state.company.selectCompanyId : this.$store.state.company.companyId

			this.getPageData()
			this.getmenbers()
		},
		watch: {
			isEditor(newdata) {
				if (newdata) {
					this.formLabelAlign.topic = ''
					this.formLabelAlign.keyWord = ''
					this.formLabelAlign.courseDate = ''
					this.formLabelAlign.startTime = ''
					this.formLabelAlign.endTime = ''
					this.formLabelAlign.timeSlot = ''
					this.formLabelAlign.experId = ''
					this.formLabelAlign.articleAttachment = ''
					this.formLabelAlign.files = []
					// this.formLabelAlign.dates = []
					this.fileListName = []
				}
			}
		},
		methods: {
			getPageData() {
				// 获取课程列表
				this.$request.postForm(this.$api.getCourse, {
					classId: this.$route.params.id
				}).then(res => {
					if (res.code == 200) {
						this.pageData = res.data
						this.rowspan()
					}
				})
			},
			headerFirst({
				row,
				colunm,
				rowIndex,
				columnIndex
			}) {
				if (rowIndex === 1) {
					//这里为了是将第二列的表头隐藏，就形成了合并表头的效果
					return {
						display: 'none'
					}

				}
				return "background:#f5f7fa"
			},
			paginaClick(val) {
				this.getPageData()
			},
			rowspan() {
				// rowspanHB
				this.dataDate.clear()
				this.pageData.items.forEach((v, i) => {
					if (this.dataDate.has(v.courseDate)) {
						let setKey = 0
						if (this.dataDate.size <= 1) {
							setKey = 0
						} else {
							setKey = this.dataDate.get(v.courseDate).key
						}
						let date = {
							key: setKey,
							val: this.dataDate.get(v.courseDate).val + 1
						}
						this.dataDate.set(v.courseDate, date)
					} else {
						let date = {
							key: i,
							val: 1
						}
						this.dataDate.set(v.courseDate, date)
					}
				})
				this.newArry = []
				this.dataDate.forEach((v, i) => {
					let data = []
					for (let q = 1; q <= v.val; q++) {
						data[0] = v.key
						data[1] = v.val
						this.newArry.push(data)
					}
				})
			},
			objectSpanMethod({
				row,
				column,
				rowIndex,
				columnIndex
			}) {
				// 合并表格
				if (columnIndex === 0) {
					if (rowIndex === this.newArry[rowIndex][0]) {
						return {
							rowspan: this.newArry[rowIndex][1],
							colspan: 1
						};
					} else {
						return {
							rowspan: 0,
							colspan: 0
						};
					}
				}
			},
			submit() {
				// 提交数据
				if (!this.formLabelAlign.topic) {
					this.$message.error('请填写课题')
					return
				} else if (!this.formLabelAlign.keyWord) {
					this.$message.error('请填写关键词')
					return
				} else if (!this.formLabelAlign.courseDate) {
					this.$message.error('请选择课程日期')
					return
				} else if (!this.formLabelAlign.startTime) {
					this.$message.error('请选择开始时间')
					return
				} else if (!this.formLabelAlign.endTime) {
					this.$message.error('请选择结束时间')
					return
				} else if (!this.formLabelAlign.timeSlot) {
					this.$message.error('请选择授课时间段')
					return
				} else if (!this.formLabelAlign.experId) {
					this.$message.error('请选择专家')
					return
				} else if (this.formLabelAlign.files.length < 1) {
					this.$message.error('请上传课件')
					return
				} else if (!this.formLabelAlign.articleAttachment) {
					this.$message.error('请添加文章')
					return
				}
				this.formLabelAlign.courseId = this.$route.params.id
				let postUrl = ''

				if (this.isLookList) {
					// 编辑
					postUrl = this.$api.updateCourse
					this.formLabelAlign.id = this.updateCourseId
				} else {
					// 新增
					postUrl = this.$api.newCourse
				}

				this.$request.postForm(postUrl, this.formLabelAlign).then(res => {
					if (res.code == 200) {
						this.$message.success('操作成功')
						this.getPageData()
						this.isEditor = false
						this.isLookList = false
					}
				})
				// console.log(this.formLabelAlign)
			},
			getmenbers() {
				// 获取专家列表
				this.$request.postForm(this.$api.queryExpertList, {
					companyId: this.companyId,
					trainingClassId: this.$route.params.id,
					page: 1,
					pageSize: 20000
				}).then(res => {
					if (res.code == 200) {
						this.menbersList = res.data
					}
				})
			},
			uploadFiles(file) {
				// 上传课件文件
				this.uploadLoading = true
				let formData = new FormData
				formData.append('file', file.file)
				formData.append('identifier', 'FILEPATH')
				this.$request.uploading(this.$api.uploadFilefileidentifier, formData).then(res => {
					if (res.code == 200) {
						this.formLabelAlign.files.push(res.data)
						this.fileListName.push(file.file.name)
						this.$message.success('上传成功')
						this.uploadLoading = false
					} else {
						this.$message.success('失败成功,请重新上传')
						this.uploadLoading = false
					}
				}).catch(e => {
					this.$message.success('失败成功,请重新上传')
					this.uploadLoading = false
				})
			},
			deleteFiles(index) {
				// 删除上传的文件
				this.$confirm('确定要删除该文件吗?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.formLabelAlign.files.splice(index, 1)
					this.fileListName.splice(index, 1)
					this.$message.success('删除成功')
				})
			},
			selectStratTime(e) {
				// 当开始时间选择的时候，清空结束时间
				Number(e.split(':')[0]) < 12 ? this.formLabelAlign.timeSlot = '上午' : this.formLabelAlign.timeSlot = '下午',
				this.formLabelAlign.endTime = ''
			},
			lookcourse(row) {
				// 查看课程
				this.isEditor = true
				this.updateCourseId = row.id
				this.$request.postForm(this.$api.getCourseDetail, {
					id: row.id
				}).then(res => {
					if (res.code == 200) {
						this.isLookList = true
						let data = res.data
						this.formLabelAlign.topic = data.topic
						this.formLabelAlign.keyWord = data.keyWord
						this.formLabelAlign.courseDate = data.courseDate
						this.formLabelAlign.startTime = data.startTime
						this.formLabelAlign.endTime = data.endTime
						this.formLabelAlign.timeSlot = data.timeSlot
						this.formLabelAlign.experId = data.experId
						this.formLabelAlign.articleAttachment = data.articleAttachment
						data.enclosureEntities.forEach((v) => {
							this.formLabelAlign.files.push(v.url)
							this.fileListName.push(v.url.split('/')[v.url.split('/').length - 1])
						})
					}
				})

			},
			deletecourse(row) {
				// 删除课程
				this.$confirm('确定要删除该课程吗?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$request.postForm(this.$api.removeCourse, {
						id: row.id
					}).then(res => {
						if (res.code == 200) {
							this.$message.success('删除成功')
							this.getPageData()
						}
					})
				})

			},
			goBack() {
				// 返回操作
				this.isEditor = false
				this.isLookList = false
			}
		}
	};
</script>

<style scoped="scoped">
	.topButton {
		padding: 10px 0;
		text-align: right;
	}

	.formInput {
		width: 500px;
	}

	.fileListName {
		width: 500px;
		padding: 0 30px 0 10px;
		position: relative;
		border: 1px solid #DCDCDC;
		margin-bottom: 15px;
		align-items: center;
		color: #5C5C5C;
		border-radius: 5px;
	}

	.fileListNameIcon {
		position: absolute;
		right: 10px;
		cursor: pointer;
		top: 10px;
	}

	.fileListNameIcon:hover,
	.dayNub {
		color: #23B14D;
	}

	.upload-demo {
		/* float: left; */
		/* margin-left: 10px; */
	}

	.EditorForm>>>.edui-default .edui-toolbar .edui-combox .edui-combox-body,
	.EditorForm>>>.edui-default .edui-button-body,
	.edui-splitbutton-body,
	.edui-menubutton-body,
	.edui-combox-body {
		line-height: 22px !important;
	}

	.EditorForm {
		padding-top: 30px;
	}

	.VueUeditorWrap {
		width: 500px;
	}

	.btnBox {
		width: 100%;
		margin-top: 30px;
		padding: 30px 0;
		border-top: 1px solid #DCDCDC;
		text-align: center;
	}

	.btnBox button {
		width: 100px;
	}
</style>
